<?php

namespace app\api\controller\verificat;

use app\admin\model\user\UserLvl;
use app\common\controller\Verifcat;
use app\common\helpers\ImageUtil;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Verifcat
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $userinfo = $this->auth->getUserinfo();
            $userinfo['avatar'] = ImageUtil::handle($userinfo['avatar']);
            $data = ['userinfo' => $userinfo];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }



    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->avatar = $avatar;
        $user->save();
        $userinfo = $this->auth->getUserinfo();
        $userinfo['avatar'] = ImageUtil::handle($userinfo['avatar']);
        $data = ['userinfo' => $userinfo];
        $this->success(__('Logged in successful'), $data);
    }


    /**
     * 刷新用户中心
     * @ApiMethod   (POST)
     */
    public function refresh()
    {
        $userinfo = $this->auth->getUserinfo();
        $userinfo['avatar'] = ImageUtil::handle($userinfo['avatar']);
        $data = ['userinfo' => $userinfo];
         $this->success(__('刷新成功'), $data);
    }

}
